import * as ExcelJS from "exceljs";
import FileSaver from "file-saver";
import _ from "lodash";

const wordIndex = [
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
];

const setCellStyle = (cell, bgColor = "FFFFFFFF") => {
  cell.alignment = {
    vertical: "middle", // 垂直居中
    horizontal: "center", // 水平居中
    wrapText: true, // 自动换行
  };
  cell.border = {
    top: { style: "thin" },
    bottom: { style: "thin" },
    left: { style: "thin" },
    right: { style: "thin" },
  };
  cell.fill = {
    type: "pattern", // 填充类型
    pattern: "solid", // 图案
    fgColor: { argb: bgColor },
  };
};

// 通用导出
const exportTable = (title, columns, rows, fileName) => {
  const workbook = new ExcelJS.Workbook();
  workbook.creator = "arrow";
  workbook.created = new Date();
  workbook.modified = new Date();
  workbook.properties.date1904 = true;

  // 添加sheet
  const worksheet = workbook.addWorksheet("报表");
  worksheet.properties.defaultColWidth = 20;
  worksheet.properties.defaultRowHeight = 20;

  const valueCell = worksheet.getCell(`A1`);
  worksheet.mergeCells(`A1:${wordIndex[columns.length - 1]}1`);
  valueCell.value = title;
  valueCell.font = { name: "宋体", family: 4, size: 12 };
  setCellStyle(valueCell);

  if (rows && rows.length > 0) {
    // 添加表格
    worksheet.addTable({
      name: `MyTable`,
      ref: `A2`,
      style: {
        theme: "TableStyleLight1",
        showRowStripes: true,
      },
      headerRow: true,
      columns,
      rows,
    });
  }

  workbook.xlsx.writeBuffer().then((buffer) => {
    FileSaver.saveAs(
      new Blob([buffer], { type: "application/octet-stream" }),
      `${fileName}.xlsx`
    );
  });
};

const exportExcel = (title, fileName, columnLength, hooks) => {
  const workbook = new ExcelJS.Workbook();
  workbook.creator = "arrow";
  workbook.created = new Date();
  workbook.modified = new Date();
  workbook.properties.date1904 = true;

  // 添加sheet
  const worksheet = workbook.addWorksheet("报表");
  worksheet.properties.defaultColWidth = 20;
  // worksheet.properties.defaultRowHeight = 20;//多行以后无效

  const valueCell = worksheet.getCell(`A1`);
  worksheet.mergeCells(`A1:${wordIndex[columnLength - 1]}1`);
  valueCell.value = title;
  valueCell.font = { name: "宋体", family: 4, size: 10 };
  setCellStyle(valueCell);

  // 调用外部钩子函数
  hooks(worksheet);

  worksheet.eachRow((row) => {
    row.height = 20;
  });

  workbook.xlsx.writeBuffer().then((buffer) => {
    FileSaver.saveAs(
      new Blob([buffer], { type: "application/octet-stream" }),
      `${fileName}.xlsx`
    );
  });
};

export { exportExcel, setCellStyle, exportTable, wordIndex };
